package com.coolwen.spring.speciality.config;

import com.coolwen.spring.speciality.model.User;
import com.coolwen.spring.speciality.path.DevPath;
import com.coolwen.spring.speciality.path.QaPath;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.ResourcePropertySource;

import javax.annotation.PostConstruct;
import java.io.IOException;

/**
 * @author CoolWen
 * @version 2020-04-02 8:47
 */
@Configuration
@Import({AConfig.class, BConfig.class})
@ComponentScan("com.coolwen.spring")
//@PropertySource({"application.properties", "application-cw.properties", "application-zs.properties"})
@PropertySource({"user.properties"})
public class BaseConfig {

    @Autowired
    private ConfigurableEnvironment env;

    @PostConstruct//该方法在构造函数之后执行
    public void initProperty() {
//        System.out.println(env.getActiveProfiles()[0]);
        try {
            if (env.getActiveProfiles().length > 0) {
                System.out.println("Yes activeFile");
                for (String ap : env.getActiveProfiles()) {
                    //
                    ClassPathResource cpr = new ClassPathResource("application-" + ap + ".properties");
                    if (cpr.exists()) {
                        env.getPropertySources().addLast(new ResourcePropertySource(cpr));
                    }
                }
            } else {
                System.out.println("No activeFile");
                ClassPathResource cpr = new ClassPathResource("application.properties");
                env.getPropertySources().addLast(new ResourcePropertySource(cpr));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Bean//<bean id="hello" value="Hello Coolwen">
    public String hello() {
        return "Hello Coolwen";
    }

    @Bean(initMethod = "init", destroyMethod = "destroy")
    public BaseObject baseObject() {
        return new BaseObject();
    }

    @Bean("path")
    @Profile("dev")
    public DevPath devPath() {
        return new DevPath();
    }

    @Bean("path")
    @Profile("qa")
    public QaPath qaPath() {
        return new QaPath();
    }


    @Bean
    @Conditional(HelloConditionCheck.class)
    public String helloCheck() {
        return "Hello Check!";
    }

    @Bean
    public User user() {
        User user = new User(env.getProperty("user.username"), env.getProperty("user.nickname"));
        return user;
    }
}
